import os
import socket
import sys
import threading


class httpServer(object):
    def __init__(self, port):
        path = os.getcwd()
        print(path)
        tcpServerSocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        tcpServerSocket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, True)
        tcpServerSocket.bind(("", port))
        print("服务器绑定端口为-", port)
        tcpServerSocket.listen(128)
        self.tcpServerSocket = tcpServerSocket

    @staticmethod
    def getReqSocket(newSockt, ipPort):
        print(ipPort)
        recvData = newSockt.recv(4096)
        if len(recvData) == 0:
            print("关闭浏览器！", ipPort)
            newSockt.close()
            return
        recvClientContent = recvData.decode("utf-8")
        reqList = recvClientContent.split(" ", 2)
        reqUrl = reqList[1]
        if reqUrl == "/":
            reqUrl = "/index.html"
        print("客服端接收的数据：", reqUrl)
        # with open("static/index.html", "rb") as file:
        try:
            with open("static" + reqUrl, "rb") as file:
                fileData = file.read()
        except Exception as e:
            responseLine = "HTTP/1.1 404 Not Found\r\n"
            responseHeader = "Server: PWS1.0\r\n"
            with open("static/error.html", "rb") as file:
                fileData = file.read()
            responseBody = fileData
            responseData = (responseLine + responseHeader + "\r\n").encode(
                "utf-8"
            ) + responseBody
            newSockt.send(responseData)
        else:
            responseLine = "HTTP/1.1 200 OK\r\n"
            responseHeader = "Server: PWS1.0\r\n"
            responseBody = fileData
            responseData = (responseLine + responseHeader + "\r\n").encode(
                "utf-8"
            ) + responseBody
            newSockt.send(responseData)
        finally:
            print("关闭套接字", ipPort)
            newSockt.close()

    def start(self):
        while True:
            newSockt, ipPort = self.tcpServerSocket.accept()
            subThreading = threading.Thread(
                target=self.getReqSocket, args=(newSockt, ipPort)
            )
            subThreading.setDaemon(True)
            subThreading.start()


def main():
    params = sys.argv
    if len(params) != 2:
        print("命令执行格式应为：XXXXX.py 8080")
        return
    if not params[1].isdigit():
        print("命令执行格式应为：XXXXX.py 8080")
        return
    port = int(params[1])
    webSever = httpServer(port)
    webSever.start()


if __name__ == "__main__":
    main()
